<?php
class IOSS_AGApi{
    const WEBSITE = "ajvip8.com";
    const HOST_GI = "http://gi.ajvip8.com:81/doBusiness.do";
    const HOST_GCI = "http://gci.ajvip8.com:81/forwardGame.do";
    const CAGENT = "CB5_AGIN";
    const USER_AGENT = "WEB_LIB_GI_CB5_AGIN";
    const ODDTYPE = "A";                                             // 下注范围,参见附件2
    const CUR = "CNY";                                               // 默认币种
    const LANGUAGE = "zh-cn";                                        // 语言
    const DES_KEY = "sqJ7UTz0";                                      // des key
    const MD5_KEY = "8Dc4NugBLLZ7";                                  // md5 key
    const ACCOUNT_PREFIX = "aj";                                     // 用户账号前缀
    
    const HTTP_TIMEOUT_MS = 30000;
    const HTTP_PROXY = "http://127.0.0.1:7070";
    
    /*
     * 创建或者登录用户
     * true  : 业务成功
     * false : 业务失败
     */
    public static function agin_check_or_create_game_account($loginname,$password,&$error_message=false,$is_test=false)
    {
        $parameters["method"] = "lg";
        self::build_parameters($parameters,$is_test);
        $parameters["loginname"] = self::ACCOUNT_PREFIX.$loginname;
        $parameters["password"] = $password;
        $parameters["oddtype"] = self::ODDTYPE;
        
        $url = self::build_url($parameters);
        if(!self::send_request($url,$response,$error_message)){
            return false;
        }
        if($response["info"]!="0"){
            $error_message["Type"] = $response["info"];
            $error_message["Message"] = $response["msg"];
            return false;
        }
        return true;
    }
    
    /*
     * 成功返回用户余额
     * false : 业务失败
     */
    public static function agin_get_balance($loginname,$password,&$error_message=false,$is_test=false)
    {
        $parameters["method"] = "gb";
        self::build_parameters($parameters,$is_test);
        $parameters["loginname"] = self::ACCOUNT_PREFIX.$loginname;
        $parameters["password"] = $password;
        
        $url = self::build_url($parameters);
        if(!self::send_request($url,$response,$error_message)){
            return false;
        }
        try{
            return $response["info"];
        }
        catch(Exception $e){
            $error_message["Type"] = $response["info"];
            $error_message["Message"] = $response["msg"];
            return false;
        }
    }
    
    /*
     * 预备转账
     * $type: 'IN' or 'OUT'
     */
    public static function agin_prepare_transfer_credit($loginname,$password,$billno,$type,$credit,&$error_message=false,$is_test=false)
    {
        $parameters["method"] = "tc";
        //todo , billno is 13 to 16 length
        if(!$credit){
            return false;
        }
        self::build_parameters($parameters,$is_test);
        $parameters["loginname"] = self::ACCOUNT_PREFIX.$loginname;
        $parameters["password"] = $password;
        $parameters["billno"] = self::CAGENT.$billno;
        $parameters["type"] = $type;
        $parameters["credit"] = $credit;
        
        $url = self::build_url($parameters);
        if(!self::send_request($url,$response,$error_message)){
            return false;
        }
        if($response["info"]!="0"){
            $error_message["Type"] = $response["info"];
            $error_message["Message"] = $response["msg"];
            return false;
        }
        return true;
    }
    
    /*
     * 确认转账
     * $type: 'IN' or 'OUT'
     * $flag: 这个参数暂时不知道怎么用
     */
    public static function agin_confirm_transfer_credit($loginname,$password,$billno,$type,$credit,&$error_message=false,$flag=1,$is_test=false)
    {
        $parameters["method"] = "tcc";
        if(!$credit){
            return false;
        }
        self::build_parameters($parameters,$is_test);
        $parameters["loginname"] = self::ACCOUNT_PREFIX.$loginname;
        $parameters["password"] = $password;
        $parameters["billno"] = self::CAGENT.$billno;
        $parameters["type"] = $type;
        $parameters["credit"] = $credit;
        $parameters["flag"] = $flag;
        $url = self::build_url($parameters);
        if(!self::send_request($url,$response,$error_message)){
            return false;
        }
        if($response["info"]!="0"){
            $error_message["Type"] = $response["info"];
            $error_message["Message"] = $response["msg"];
            return false;
        }
        return true;
    }
    
    /*
     * 查询转账订单状态
     */
    public static function agin_query_transfer_status($billno,&$error_message=false,$is_test=false)
    {
        $parameters["method"] = "qos";
        self::build_parameters($parameters,$is_test);
        $parameters["billno"] = self::CAGENT.$billno;
        $url = self::build_url($parameters);

        if(!self::send_request($url,$response,$error_message)){
            return false;
        }


        if($response["info"]!="0"){
            $error_message["Type"] = $response["info"];
            $error_message["Message"] = $response["msg"];
            return false;
        }
        return true;
    }
    
    /*
     * 获取游戏url链接
     * 文档中要求必须将该链接以form提交.
     */
    public static function agin_get_game_url($loginname,$password,$gametype,$sid,$session_token,&$error_message=false,$is_test=false)
    {
        self::build_parameters($parameters,$is_test);
        $parameters["dm"] = self::WEBSITE;
        $parameters["lang"] = self::LANGUAGE;
        $parameters["loginname"] = self::ACCOUNT_PREFIX.$loginname;
        $parameters["password"] = $password;
        $parameters["gameType"] = $gametype;
        $parameters["sid"] = self::CAGENT.$sid;
        $parameters["session_token"] = $session_token;
        $url = self::build_url($parameters,true);
        return $url;
    }
    
    /**
     * 发送请求
     */
    public static function send_request($url,&$response,&$error_message){
        $setting["user_agent"] = self::USER_AGENT;
        $request_result = self::http_post($url,null,$response_xml,$error_message,$setting);
        if(!$request_result){
            return false;
        }
        if(!$response_xml){
            $error_message["Type"] = "response is null";
            $error_message["Code"] = "";
            return false;
        }
        try{
            $xml = simplexml_load_string($response_xml);
        }
        catch(Exception $e){
            $error_message["Type"] = "parse xml error";
            $error_message["Code"] = "";
            return false;
        }
        $response["info"] = (string)$xml["info"];
        $response["msg"]  = (string)$xml["msg"];
        return true;
    }
    
    /**
     *  构建参数 
     */
    public static function build_parameters(&$parameters,$is_test){
        if($is_test){
            $parameters["actype"] = 0;
        }else{
            $parameters["actype"] = 1;
        }
        $parameters["cur"] = self::CUR;
        $parameters["cagent"] = self::CAGENT;
    }
    
    /***
     *  构建url
     */ 
    public static function build_url($parameters,$is_gci=false){
        $query_str = http_build_query($parameters);
        $query_replaced = str_replace("&","/\\\\\\\\/",$query_str);             // api需要的字符串替换
        $des_str = self::agin_des_encrypt($query_replaced,self::DES_KEY);                  // des encrypt
        $md5_str = self::agin_md5_hash($des_str,self::MD5_KEY);                            // md5 hash
        $new_parameters["params"] = $des_str;
        $new_parameters["key"] = $md5_str;
        if($is_gci){
            $url =self::HOST_GCI."?". "params=".$des_str."&key=".$md5_str;
        }else{
            $url =self::HOST_GI."?". http_build_query($new_parameters);
        }
        return $url;
    }
    
    // md5
    public static function agin_md5_hash($str,$md5_key){
        return md5($str.$md5_key);
    }
    // des
    public static function agin_des_encrypt($input,$key) {
        $size = mcrypt_get_block_size('des', 'ecb');
        $input = self::pkcs5_pad($input, $size);
        $key = $key;
        $td = mcrypt_module_open('des', '', 'ecb', '');
        $iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        @mcrypt_generic_init($td, $key, $iv);
        $data = mcrypt_generic($td, $input);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        $data = base64_encode($data);
        return preg_replace("/\s*/", '',$data);
    }
    
    public static function decrypt($encrypted,$key) {
        $encrypted = base64_decode($encrypted);
        $key =$key;
        $td = mcrypt_module_open('des','','ecb','');
        //使用 MCRYPT_DES 算法,cbc 模式
        $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        $ks = mcrypt_enc_get_key_size($td);
        @mcrypt_generic_init($td, $key, $iv);
        //初始处理
        $decrypted = mdecrypt_generic($td, $encrypted);
        //解密
        mcrypt_generic_deinit($td);
        //结束
        mcrypt_module_close($td);
        $y=self::pkcs5_unpad($decrypted);
        return $y;
    }
    
    public static function pkcs5_pad ($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
    
    public static function pkcs5_unpad($text) {
        $pad = ord($text{strlen($text)-1});
        if ($pad > strlen($text))
            return false;
            if (strspn($text, chr($pad), strlen($text) - $pad) != $pad)
                return false;
                return substr($text, 0, -1 * $pad);
    }
    /**
     * 具体http请求
     */
    public static function http_post($url,$post_data,&$response_body,&$error_message,$setting=null){
        $http_proxy = self::HTTP_PROXY;
        $http_timeout_ms = self::HTTP_TIMEOUT_MS;
        //初始化
        $curl = curl_init();
        //设置User Agent
        curl_setopt($curl, CURLOPT_USERAGENT,$setting["user_agent"]);
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // 设置代理服务器,调试用
        if($http_proxy){
            curl_setopt ($curl, CURLOPT_PROXY, $http_proxy);
        }
        // 超时
        curl_setopt($curl, CURLOPT_NOSIGNAL, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT_MS, $http_timeout_ms);
        if($post_data){
            //设置post方式提交
            curl_setopt($curl, CURLOPT_POST, 1);
            // 设置post data
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post_data));
        }
        //执行命令
        $response = curl_exec($curl);
        // 判断是否执行成功
        if (curl_errno($curl) != 0)
        {
            $error_message["Type"] = "net work error";
            $error_message["Code"] = curl_errno($curl);
            return false;
        }
        // 判断http code
        $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($http_code != '200') {
            $error_message["Type"] = "http code error";
            $error_message["Code"] = $http_code;
            curl_close($curl);
            return false;
        }
        // 请求成功
        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $header = substr($response, 0, $headerSize);
        $response_body = substr($response, $headerSize);
        curl_close($curl);
        return true;
    }
	
}